package com.yuyue.springFramework.note11.entity.springCode1;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean;

import java.util.concurrent.Executor;

@Configuration
@ComponentScan
public class MyConfig5 {
    /**
     * 定义线程池参数
     * @return
     */
    @Bean
    public ThreadPoolExecutorFactoryBean applicationEventMulticasterThreadPool(){
        //创建线程池
        ThreadPoolExecutorFactoryBean executor = new ThreadPoolExecutorFactoryBean();
        //定义线程名称前缀
        executor.setThreadNamePrefix("广播器异步线程-");
        //定义线程数
        executor.setCorePoolSize(5);
        return executor;
    }

    /**
     * 注册广播器 Bean，Spring会发现有名为applicationEventMulticaster的Bean就会使用它作为广播器
     * @return
     */
    @Bean
    public ApplicationEventMulticaster applicationEventMulticaster(){
        //Spring提供的简单广播器实现类
        SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
        //从自定义的线程池获取 Executor
        Executor executor = this.applicationEventMulticasterThreadPool().getObject();

        //当广播器指定 Executor 后，会使用异步广播事件，具体见源码 SimpleApplicationEventMulticaster.multicastEvent
        multicaster.setTaskExecutor(executor);
        return multicaster;
    }
}
